package com.loveyukari.service;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import com.loveyukari.model.Auth;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.util.HtmlUtils;

import com.loveyukari.support.SocketResult;

import net.sf.json.JSONObject;

/**
*
*yangshaohua
*2017年10月10日下午4:58:33
**/
@Service
public class YukariWebSocketService {
	
	
	@Autowired
	private WebSocketService webSocketService;
	
	private Logger socketLog = LoggerFactory.getLogger("socket");
	
	private Set<WebSocketSession> ss = new HashSet<WebSocketSession>();
	
	
	public void openChatmsgWebSocket(WebSocketSession session){
		ss.add(session);
	}
	
	
	public void sendChatmsg(JSONObject data){
		SocketResult socketResult = new SocketResult();
		socketResult.setType("chatmsg");
		String txt = data.optString("txt");
		data.put("txt", HtmlUtils.htmlEscape(txt));
		socketResult.setData(data);
		send(socketResult);
	}

	public void sendUenter(JSONObject data){
		SocketResult socketResult = new SocketResult();
		socketResult.setType("uenter");
		socketResult.setData(data);
		send(socketResult);
	}

	public void sendHorn(JSONObject data){
		SocketResult socketResult = new SocketResult();
		socketResult.setType("horn");
		JSONObject result = new JSONObject();
		if(StringUtils.equals("cthn",data.optString("type"))){
			result.put("txt",HtmlUtils.htmlEscape(data.optString("chatmsg")));
			result.put("name",data.optString("unk"));
		} else if(StringUtils.equals("ssd",data.optString("type"))){
			result.put("txt",HtmlUtils.htmlEscape(data.optString("content")));
			result.put("name","超级弹幕");
		}
		socketResult.setData(result);
		send(socketResult);
	}

	private void send(SocketResult socketResult){
		Iterator<WebSocketSession> iterator = ss.iterator();
		while (iterator.hasNext()) {
			WebSocketSession webSocketSession = iterator.next();
			if (webSocketSession.isOpen()){
				try {
					webSocketService.sendMessage(webSocketSession, socketResult.toString());
				} catch (IOException e) {
					socketLog.error(e.getMessage(),e);
				}
			} else {
				ss.remove(webSocketSession);
			}
		}
	}
}
